<?php

namespace app\store\controller;

use app\store\model\User as UserModel;
use app\common\model\GetTui as GetTuiModel;
use app\store\model\Setting as SettingModel;

use app\store\model\Region;

/**
 * 用户管理
 * Class User
 * @package app\store\controller
 */
class User extends Controller
{
    /**
     * 用户列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
		$where = [];
		$wherenew = '';
		$datetime = $this->request->param('datetime/s' ,'');
		if( $datetime ) {
			$datetime = explode(" ~ " , $datetime);
			$where['open_cart_time'] = [['egt' , strtotime($datetime[0])],['elt' , strtotime($datetime[1]) + 24 * 3600 - 1]];
			//print_r( $where );die;
		}
		$string = $this->request->param('string' , '');
		if( $string ) {
			$wherenew = "`mobile` = '{$string}' OR `cart_sn` = '{$string}' OR `nickname` = '{$string}'";
		}
		$is_cart = $this->request->param('is_cart/d' , 0);
		if( $is_cart > 0 ) {
			$where['is_open_cart'] = $is_cart - 1;
		}
		$province = $this->request->param('province/d' , 0);
		if( $province > 0 ) {
			$where['province'] = $province;
		}
		$city = $this->request->param('city/d' , 0);
		if( $city > 0 ) {
			$where['city'] = $city;
		}
		$area = $this->request->param('area/d' , 0);
		if( $area > 0 ) {
			$where['area'] = $area;
		}
        $model = new UserModel;
        $list = $model->getList( $where , $wherenew );
		$area = json_encode(Region::getCacheTree());
		//会员卡统计
		$data = [];
		$user_data = $is_cart != 1 ? db('user')->where(array_merge($where,['is_open_cart' => 1]))->column("user_id") : [];
		$price = '0.00';
		$rest_price = '0.00';
		$total_price = '0.00';
		$rest_cart_order = [];
		if( $user_data ) {
			$cart_order = db('member_cart_order')->where(['user_id' => ['in' , $user_data] , 'status' => 1])->field("id,price")->select()->toArray();
			$price = array_sum(array_column($cart_order,'price'));
			$total_price = db('member_cart_order_distribution')->where(['member_cart_order_id' => ['in' , array_column($cart_order,'id')],'status' => 1])->sum("price");
			$rest_cart_order = db('member_cart_order')->where(['user_id' => ['in' , $user_data],'restart' => 1 , 'status' => 1])->field("id,price")->select()->toArray();
			$rest_price = array_sum(array_column($rest_cart_order,'price'));
		}
		$data = [
			'open_man_num' => count($user_data),
			'open_man_price' => $price,
			'total_price' => $total_price,
			'open_rest_man_num' => count($rest_cart_order),
			'open_rest_man_price' => $rest_price
		];
		if( $list ) {
			foreach( $list as $k => $v ) {
				$list[$k]['parent_nickname'] = '无';
             	$list[$k]['parent_mobile'] = '--';
				if( $v['parent_id'] > 0 ) {
					$list[$k]['parent_nickname'] = db("user")->where(['user_id' => $v['parent_id']])->value("nickname");
					$list[$k]['parent_mobile'] = db("user")->where(['user_id' => $v['parent_id']])->value("mobile");
				}
			}
		}
        return $this->fetch('index', compact('list','area' , 'data'));
    }
    
    
    /**
     * 新增用户
     */
    public function add() {
        return $this->post();
    }
    
    /**
     * 用户修改
     */
    public function edit() {
        $id = $this->request->param('id/d' , 0);
        if( $id <= 0 ) $this->error('数据格式错误');
        $user = db("user")->where(['user_id' => $id])->find();
        if( !$user ) $this->error('数据不存在，请核对');
		if( $user['parent_id'] ) {
			$user['user_info'] = db("user")->where(['user_id' => $user['parent_id']])->find();
        }
		return $this->post( $user );
    }
    
    /**
     * 数据操作
     */
    private function post( $user = '') {
        if( $this->request->isAjax() ) {
            $model = new UserModel;
            $params = $this->postData('user');
            $params['province_name'] = db("region")->where(['id' => $params['province']])->value("name");
            $params['city_name'] = db("region")->where(['id' => $params['city']])->value("name");
            $params['area_name'] = db("region")->where(['id' => $params['area']])->value("name");
			isset( $params['avatar'] ) && $params['avatar'] ? '' : $params['avatar'] = '/assets/default/default.jpg';
            $id = $this->request->post('id/d' , 0);
            if( $id <= 0 ) {
				if( !preg_match('/^1[3-9][0-9]{9}$/is' , $params['mobile']) ) {
					$this->error('手机号格式错误，请重新输入');
				}
                //判断手机号是否重复
                if( $model->where(['mobile' => $params['mobile']])->find()) {
                    $this->error('手机号已存在，请更换手机号');
                }
                $params['password'] = $model->passmd5($params['password']);
                $params['create_time'] = time();
				$share = db("user")->order("share_code DESC")->value("share_code");
				$params['share_code'] = ( $share ? $share : 1000000 ) + rand(20 , 50);
                $res = $model->insert($params);
                if( $res ) {
                    $this->success('用户新增成功');
                } else {
                    $this->error('用户新增失败');
                }
            } else {
                if( $params['password'] == '') {
                    unset( $params['password'] );
                }else {
                    $params['password'] = $model->passmd5($params['password']);
                }
                $params['update_time'] = time();
                $res = $model->where(['user_id' => $id])->update($params);
                if( $res ) {
                    $this->success('用户修改成功');
                } else {
                    $this->error('用户修改失败');
                }
            }
        }
        $area = json_encode(Region::getCacheTree());
        return $this->fetch('' , compact('area' , 'user'));
    }
    
    public function delete() {
        $id = $this->request->post('id/d' , 0);
        if( $id <= 0 ) $this->error('参数错误，请核对');
        $res = db('user')->where(['user_id' => $id])->delete();
        if( $res ) {
            $this->success('删除成功');
        } else {
            $this->error("操作失败");
        }
    }
    
    public function savepass() {
        $id = $this->request->param('user_id/d' , 0);
        if( $id <= 0 ) $this->error('参数错误，请核对');
        $model = new UserModel;
        $info = $model->where(['user_id' => $id])->find();
        if( !$info ) $this->error('数据不存在，请核对');
        $result = $model->where(['user_id' => $id])->update(['password' => $model->passmd5('888888')]);
		$obj = new  GetTuiModel;
		$obj->sendToClient($info['user_id'] , '消息通知' , '您的密码平台已帮您重置成【888888】，请立即登录APP进行密码修改。');
        $this->success('密码重置成功');
    }
    
    public function savestatus() {
        $id = $this->request->param('user_id/d' , 0);
        $status = $this->request->param('status/d' , 0);
        if( $id <= 0 ) $this->error('参数错误，请核对');
        $model = new UserModel;
        $info = $model->where(['user_id' => $id])->find();
        if( !$info ) $this->error('数据不存在，请核对');
        $result = $model->where(['user_id' => $id])->update(['status' => $status]);
        if( $result ) {
            $this->success('操作成功');
        } else {
            $this->error("操作失败");
        }
    }
    
    public function recharge() {
        $id = $this->request->param('id/d' , 0);
        $num = $this->request->param('num/d' , 0);
        $type = $this->request->param('type/d' , 0);
        $note = $this->request->param('note');
        if( $id <= 0 ) $this->error('参数错误，请核对');
        $model = new UserModel;
        $info = $model->where(['user_id' => $id])->find();
        if( !$info ) $this->error('数据不存在，请核对');
        if( $type == 1 ) { //余额充值
            $field = 'money';
            $content = '通过后台充值余额：' . $num . '元';
        } else { //积分充值
            $field = 'integral';
            $content = '通过后台充值积分：' . $num . '元';
        }
        $result = $model->where(['user_id' => $id])->update([$field => $info[$field] + $num , 'total_' . $field => $info['total_' . $field] + $num]);
        if( $result ) {
            //写入日志
            db("user_".$field."_log")->insert([
                'user_id' => $id,
                'num' => $num,
                'content' => $content . ( $note == '' ? '' : '，备注：' .$note ) ,
                'type' => $num >= 0 ? 1 : 2,
                'create_time' => time()
            ]);
			$obj = new  GetTuiModel;
			$obj->sendToClient($info['user_id'] , '充值消息提示' , '平台已为您充值【'.$num.'】'.($type == 1?'元':'积分').',详情请在个人中心查看');
            $this->success('充值成功');
        } else {
            $this->error("充值失败，请重试");
        }
    }
	
	/**
	 * 导出
	 */
	public function export() {
		$where = [];
		$wherenew = '';
		$datetime = $this->request->param('datetime/s' ,'');
		if( $datetime ) {
			$datetime = explode(" ~ " , $datetime);
			$where['open_cart_time'] = [['egt' , strtotime($datetime[0])],['elt' , strtotime($datetime[1]) + 24 * 3600 - 1]];
			//print_r( $where );die;
		}
		$string = $this->request->param('string' , '');
		if( $string ) {
			$wherenew = "`mobile` = '{$string}' OR `cart_sn` = '{$string}' OR `nickname` = '{$string}'";
		}
		$is_cart = $this->request->param('is_cart/d' , 0);
		if( $is_cart > 0 ) {
			$where['is_open_cart'] = $is_cart - 1;
		}
		$province = $this->request->param('province/d' , 0);
		if( $province > 0 ) {
			$where['province'] = $province;
		}
		$city = $this->request->param('city/d' , 0);
		if( $city > 0 ) {
			$where['city'] = $city;
		}
		$area = $this->request->param('area/d' , 0);
		if( $area > 0 ) {
			$where['area'] = $area;
		}
		$list = db("user")->where($where)->field("user_id,nickname,sex,money,integral,mobile,province_name,city_name,area_name,identity,is_open_cart,cart_sn,service_num,login_ip,login_time,create_time,parent_id")->select()->toArray();
		$field = ['用户ID','用户昵称','性别','余额' , '积分','手机号','省','市','区','角色等级','是否开卡','会员卡号','剩余换油次数','登录IP','登录时间','创建时间','上级昵称','上级ID'];
		if( $list ) {
			$js_field = [0 => '普通会员',10 => '业务员',20 => '销售经理',30 => '总经理'];
			foreach( $list as $k => $v ) {
				$list[$k]['create_time'] = date("Y-m-d H:i:s" , $v['create_time']);
				$list[$k]['login_time'] = $v['login_time'] > 0 ? date("Y-m-d H:i:s" , $v['login_time']) : '--';
				$list[$k]['identity'] = $js_field[$v['identity']];
				$list[$k]['is_open_cart'] = $v['is_open_cart'] == 1 ? '已开卡' : '未开卡';
				$list[$k]['sex'] = $v['sex'] == 1 ? '男' : ($v['sex'] == 2 ? '女':'未设置');
				$list[$k]['level_name'] = $v['parent_id'] > 0 ? db("user")->where(['user_id' => $v['parent_id']])->value("nickname") : '--';
			}
		}
		\app\common\extend\Excel::export($list , $field);
	}
	
	public function itemshow() {
		$user_id = $this->request->param("user_id/d" , 0);
		if( $user_id <= 0 ) exit("数据异常");
		$item_show = 1;
		$user_info = db("user")->where(['user_id' => $user_id])->find();
		$user_data = [];
		$list = $this->friend( $user_id , $user_data );
		//$list = array_merge($user_info ? $user_info : [] , $list);
		$data = [
			[
				'name' => $user_info['nickname'] ? $user_info['nickname'] : '我自己',
				'code' => $user_info['user_id'],
				'icon' => "icon-th",
				'child' => $list
			]
		];
		$end = strtotime(date("Y-m-d 23:59:59" , time()));
		$start = strtotime(date("Y-m-d",time()));
		
		//统计
		$count = [
			'total' => 0,
			'total_price' => 0,
			'total_item' => 0,
			'total_cart' => 0,
			'total_1' => 0,
			'total_2' => 0,
			'total_3' => 0,
			'today' => 0,
			'day7' => 0,
			'day15' => 0,
		];
		
		if( $user_data ) {
			$count = [
				'total' => count($user_data),
				'total_price' => db("member_cart_order")->alias("co")->join("yoshop_user u","u.user_id = co.user_id")->where(['co.user_id' => ['IN' , implode(',' , $user_data)],'co.status' => 1 , 'u.is_open_cart' => 1])->sum('price'),
				'total_item' => db("user")->where(['user_id' => ['IN' , implode(',' , $user_data)],'status' => 2 , 'is_item' => 1])->count(),
				'total_cart' => db("user")->where(['user_id' => ['IN' , implode(',' , $user_data)],'status' => 2 , 'is_open_cart' => 1])->count(),
				'total_1' => db("user")->where(['user_id' => ['IN' , implode(',' , $user_data)],'status' => 2 , 'identity' => 10])->count(),
				'total_2' => db("user")->where(['user_id' => ['IN' , implode(',' , $user_data)],'status' => 2 , 'identity' => 20])->count(),
				'total_3' => db("user")->where(['user_id' => ['IN' , implode(',' , $user_data)],'status' => 2 , 'identity' => 30])->count(),
				'today' => db("user")->where('`user_id` IN('. implode(',' , $user_data) .') AND `create_time` >= ' . $start . ' AND `create_time` <= ' . $end)->count(),
				'day7' => db("user")->where('`user_id` IN('. implode(',' , $user_data) .') AND `create_time` >= ' . ( $start - ( 15 * 3600 * 24 - 1 ) ) . ' AND `create_time` <= ' . $end)->count(),
				'day15' => db("user")->where('`user_id` IN('. implode(',' , $user_data) .') AND `create_time` >= ' . ( $start - ( 30 * 3600 * 24 - 1 ) ) . ' AND `create_time` <= ' . $end)->count(),
			];
		}
		return $this->fetch('show' ,compact('item_show' , 'data' , 'count' ));
	}
	
	private function friend($id , &$data) {
		if( !$id ) return '';
        $sf_field = [0 => '普通会员',10 => '业务员',20 => '销售经理',30 => '总经理'];
		$user = db("user")->where(['parent_id' => $id , 'status' => 2])->field("user_id AS code,nickname AS name,identity,parent_id AS parentCode,is_item")->select()->toArray();
		if( $user ) {
			foreach( $user as $k => $v) {
				$data[] = $v['code'];
				$user[$k]['name'] = $user[$k]['name'] . ' 等级：' . $sf_field[$v['identity']] . ( $v['is_item'] == 1 ? '团长已开通' : '' );
				unset( $user[$k]['identity'] );
				$list = $this->friend( $v['code'] , $data );
				$user[$k]['icon'] = '';
				$user[$k]['child'] = [];
				if( $list ) {
					$user[$k]['icon'] = 'icon-minus-sign';
					$user[$k]['child'] = $list;
				}
			}
		}
		return $user;
	}
	
	public function opencart() {
		$user_id = $this->request->param("user_id/d" , 0);
		if( $user_id <= 0 ) $this->error("数据异常");
		$user_info = db("user")->where(['user_id' => $user_id])->find();
		if( !$user_info ) $this->error("数据异常");
		
		$data = SettingModel::getItem('distribution');
		if( isset( $data['order_price'] ) && $data['order_price'] > 0 ) {
			$info = [
				'ordersn' => date("YmdHis") . rand(1000 , 9999),
				'user_id' => $user_id,
				'price' => $data['order_price'],
				'service_num' => $data['order_consumption_num'],
				'pay_type' => 4,
				'pay_time' => time(),
				'transaction_id' => date("YmdHis") . rand(100000 , 999999),
				'restart' => $user_info['is_open_cart'],
				'status' => 1,
				'create_time' => time()
			];
			$result = db("member_cart_order")->insert( $info );
			$order_id = db("member_cart_order")->getLastInsID();
			if( $result ) {
				//推荐奖励
				$usermodel = new UserModel;
				$usermodel->builddistribution( $info['ordersn'] );
				//团队奖励
				//$usermodel->colonelReward($user_id , $order_id);
				$obj = new  GetTuiModel;
				$obj->sendToClient($user_id , ( $user_info['is_open_cart'] == 1 ? '会员卡续卡成功' : '会员卡开通成功' ) , ( $user_info['is_open_cart'] == 1 ? '平台已为您续卡，详情请在个人中心查看' : '平台已为您开通会员卡，详情请在个人中心查看' ) );
				$this->success("会员开通成功");
			} else {
				$this->error("开通失败");
			}
		} else {
			$this->error("请联系管理员，错误码：30001");
		}
	}
}
